import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { ApiService } from 'src/app/core/api';

@Component({
    selector: 'app-menu',
    templateUrl: './menu.component.html',
    styleUrls: ['./menu.component.scss'],
})
export class MenuComponent implements OnInit {
    url: string;
    routerData: any;
    menuList = [];
    @Input()
    isCollapsed: boolean;

    @Output()
    menuEvent: EventEmitter<string> = new EventEmitter<string>();

    constructor(private router: Router, private apiService: ApiService, private activatedRoute: ActivatedRoute) {
        this.apiService.post('获取当前用户的权限路径', {}).then((res: any) => {
            this.menuList = this.getTree(res.data.permission);
        });
    }

    ngOnInit() {
        let temp = this.activatedRoute;
        while (temp.firstChild) {
            temp = temp.firstChild;
        }
        this.routerData = temp.snapshot.data;
    }
    public gotoPage(e) {
        this.router.navigate([e.frontPath]);
    }
    getTree(list) {
        const array = [],
            obj = {};
        list.forEach(element => {
            if (element.parentId === 0) {
                array.push(element);
            }
            if (element.frontPath && element.frontPath.indexOf(this.routerData.url) !== -1) {
                element.isOpen = true;
            }
            obj[element.id] = element;
        });
        list.forEach(element => {
            if (obj[element.parentId]) {
                obj[element.parentId].children ? obj[element.parentId].children.push(element) : (obj[element.parentId].children = [element]);
            }
        });
        return array;
    }
    clickSubMenu(item) {
        if (!item.isOpen) {
            item.isOpen = !item.isOpen;
            if (item.frontPath) {
                this.router.navigate([item.frontPath]);
                return false;
            } else {

            }
        }
    }
    selectMenu(item) {
        this.menuList.forEach(element => {
            if (element.id !== item.id) {
                element.isOpen = false;
            }
        });
    }
}
